package cn.shentianlan.interceptor;

import cn.shentianlan.domain.User;
import cn.shentianlan.service.UserService;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 用于判断是否是首次使用系统，是则跳转到注册页面，否则允许通过
 */
public class RegisterInterceptor implements HandlerInterceptor {

    @Resource
    private UserService userService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        User loginUser = (User) session.getAttribute("loginUser");
        if (userService.getUserNumber()==0){//首次使用系统
            request.getRequestDispatcher("/WEB-INF/pages/register.html").forward(request,response);
        }else {
            if (loginUser == null){//没有登录
                request.getRequestDispatcher("/login.html").forward(request,response);
            }else {//已登录
                request.getRequestDispatcher("/WEB-INF/pages/monitoring.jsp").forward(request,response);
            }
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
